/*报名名单（团体） */
<template>
    <div>
        <div v-if="indexKey === 1">
            <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
            <el-row :gutter="24" style="height: 50px;">
                <!-- 学院 --> 
                <el-col :span="8">
                    <el-form-item :label="$t('registrationList.college')">
                        <DictSelect v-model="queryForm.condition.faculty" filterable :data="options.faculty" :plzSelect="true"></DictSelect>          
                    </el-form-item>
                </el-col>
                <!-- 报名状态 --> 
                <el-col :span="8">
                    <el-form-item :label="$t('registrationList.registrationStatus')">
                        <!-- <el-input v-model.trim="queryForm.condition.name" style="width:100%"></el-input> -->
                        <el-select collapse-tags  v-model="queryForm.condition.status"  filterable clearable  style="width: 100%">
                          <el-option  v-for="item in registrationStatus" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- 年度 -->
                <el-col :span="8">
                    <el-form-item :label="$t('registrationList.year')">
                        <el-date-picker style="width:100%"
                          v-model="queryForm.condition.year"
                          @change="changeYear"
                          :placeholder="$t('registrationList.pleaseSelectYear')"
                          type="year" value-format="yyyy" format="yyyy">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <!-- 学号 -->
                <el-col :span="8">
                    <el-form-item :label="$t('registrationList.studentId')">
                        <el-input v-model.trim="queryForm.condition.studentId" :placeholder="$t('registrationList.pleaseEnter')" clearable style="width: 100%" />
                    </el-form-item>
                </el-col>
                <!-- 姓名 -->
                <el-col :span="8">
                    <el-form-item :label="$t('registrationList.studentName')">
                        <el-input v-model.trim="queryForm.condition.studentName" :placeholder="$t('registrationList.pleaseEnter')" clearable style="width: 100%" />
                    </el-form-item>
                </el-col>
                <!-- 竞赛名称 -->
                <el-col :span="8">
                    <el-form-item :label="$t('registrationList.competitionNames')">
                        <el-select collapse-tags @change="changeSubname" v-model="queryForm.condition.competitionId"  filterable clearable remote :remote-method="remoteMethodName" style="width: 100%">
                            <el-option  v-for="item in options.competitionNames" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- 竞赛小类 -->
                <el-col :span="8">
                  <el-form-item :label="$t('registrationList.competitionCate')">
                    <el-select v-model="queryForm.condition.subId" clearable style="width: 100%">
                      <el-option
                        v-for="item in options.subName"
                        :key="item.id"
                        :label="item.subName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- 校区 -->
                <el-col :span="8">
                  <el-form-item :label="$t('performanceManagement.campus')">
                    <el-select v-model="queryForm.condition.campus" clearable style="width: 100%">
                      <el-option
                        v-for="item in options.campus"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
            </el-row>
            </condition-card>
            <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
                <h1 class="condition-title">{{$t('registrationList.registrationListTeam')}}</h1>
                <el-row style="padding:15px;" class="row-bg" justify="space-between">
                    <el-button
                        style="float:right; margin-left:10px;"
                        @click="noSelection"
                        >{{$t('registrationList.batchFailure')}}</el-button>
                    <el-button
                        style="float:right; margin-left:10px;"
                        @click="exportFile"
                        >{{$t('registrationList.export')}}</el-button>
                    <el-button
                        type="primary"
                        style="float:right; margin-left:10px;"
                        @click="selectionCompleted"
                        >{{$t('registrationList.selection')}}</el-button>
                </el-row>
                
            <el-table :pagination="false" :order="false" :selection='true' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange" :span-method="objectSpanMethod">
                <el-table-column type="selection" width="55" />
                <el-table-column :label="$t('registrationList.competitionName')" prop="projectName" show-overflow-tooltip></el-table-column>
                <el-table-column :label="$t('registrationList.competitionCate')" prop="subName" show-overflow-tooltip></el-table-column>
                <el-table-column :label="$t('registrationList.titleOfTheWork')" prop="workName" show-overflow-tooltip></el-table-column>
                <el-table-column align='center' :label="$t('registrationList.personnelInformation')">
                    <el-table-column :label="$t('registrationList.college')" prop="faculty" show-overflow-tooltip></el-table-column>
                    <el-table-column :label="$t('competitionRegistrationRules.major')" prop="profession" show-overflow-tooltip></el-table-column>
                    <el-table-column :label="$t('registrationList.studentId')" prop="studentId" show-overflow-tooltip></el-table-column>
                    <el-table-column :label="$t('registrationList.studentName')" prop="studentName" show-overflow-tooltip></el-table-column>
                    <el-table-column :label="$t('registrationList.sex')" prop="sex" show-overflow-tooltip width="70"></el-table-column>
                    <el-table-column :label="$t('registrationList.telephoneNumber')" prop="telephone" show-overflow-tooltip></el-table-column>
                    <el-table-column :label="$t('registrationList.mail')" prop="mail" show-overflow-tooltip></el-table-column>
                    <el-table-column :label="$t('registrationList.classTeacher')" width="120" prop="classTeacher" show-overflow-tooltip></el-table-column>
                    <el-table-column :label="$t('performanceManagement.campus')" prop="campusName" show-overflow-tooltip width="100"></el-table-column>
                </el-table-column>
                <el-table-column :label="$t('registrationList.Instructor')" prop="teacher" show-overflow-tooltip></el-table-column>
                <el-table-column :label="$t('registrationList.registrationStatus')" prop="status">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.status === '1'" type="info" plain>{{$t('registrationList.registered')}}</el-button>
                        <el-button v-else-if="scope.row.status === '2'" type="info" plain>{{$t('registrationList.selecting')}}</el-button>
                        <el-button v-else-if="scope.row.status === '3'" type="success" plain>{{$t('registrationList.passed')}}</el-button>
                        <el-button v-else-if="scope.row.status === '4'" type="info" plain>{{$t('registrationList.exited')}}</el-button>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('registrationList.actionBar')">
                    <template slot-scope="scope">
                        <!-- <el-button type="text" @click="submitResults(props.row,props.$index, 'edit')">{{$t('projectDeclara.compile')}}</el-button> -->
                        <el-button type="text" @click="publish(scope.row,scope.$index, 'publish')">{{$t('registrationList.personnelChange')}}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row type="flex" class="row-bg" justify="end">
                <el-col>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryForm.pageNum_"
                    :page-sizes="[20, 40, 80, 100]"
                    :page-size="queryForm.pageSize_"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="queryForm.total_"
                    style="float:right;margin-top:10px"
                    ></el-pagination>
                </el-col>
            </el-row>
            </el-card>
            <edu-export-dialog
                :disabled="exportButton"
                :title="$t('message.prompt')"
                ref="downloadRef"
                :data="exportResult">
            </edu-export-dialog>
        </div>
        
        <!-- 人员变更 -->
        <div v-if="indexKey === 2">
            <agentRegistration
                :compile="compile"
                :dataInfo="dataInfo"
                @change-exam="changeExamTeam"
            >
            </agentRegistration>
        </div>
    </div>
</template>
<script>
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import { findTeacherInfoList } from 'common/src/api/studentinfo';
import competiManagementApi from 'common/src/api/subjectCompetition/competiManagement';
import agentRegistration from './agentRegistration';
import competitionRegistrationApi from 'common/src/api/competitionRegistration/competitionRegistration';
import comRegistration from 'common/src/api/competitionRegistration/comRegistration'
export default {
  components: {
      agentRegistration: agentRegistration
  },
  data () {
    return {
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
        condition:{
          campus: '',
          subId: '',
          form: 1, // 竞赛类型(0个人1团体)
          // year: new Date().getFullYear(),
          year: new Date().getFullYear()+'',
          faculty: '', // 学院
          competitionId: '', // 竞赛名称
          studentName: '', // 姓名
          studentId: '', // 学号
          status: '' // 状态(1.已报名 2.选拔中 3.选拔通过 4.已退出)
        }
      },
      options: {
        campus: [],
        subName: [],
        faculty: [], // 学院
        approver: [],
        profession: [], // 竞赛名称
        degreeType: [], // 竞赛级别
        competitionNames: [] // 竞赛名称
      },
      exportButton: false,
      exportResult: null,
      multipleSelection: [],
      formsLearn: [],
      dataList: [],
      spanArr: [], // 一个空的数组，用于存放每一行记录的合并数
      pos: 0, // spanArr 的索引
      contentSpanArr: [],
      position: 0,
      indexKey: 1,
      registrationStatus: [
        {
          value: 1,
          label: '已报名'
        },
        {
          value: 2,
          label: '选拔中'
        },
        {
          value: 3,
          label: '选拔通过'
        }
      ],
      noPassList: [],
      dataInfo: {} // 人员变更信息
    }
  },
  mounted() {
    this.getOptions() 
    this.postProjectInform(this.queryForm)
    this.getCompetitionNames()
  },
  filters: {
    collegeAcademyList(val, array) {
      let str = "";
      for (let item of array) {
        if (val === item.value) {
          str = item.label;
        }
      }
      return str;
    }
  },
  methods: {
    changeSubname() {
      this.queryForm.condition.subId = ''
      this.options.subName = []
      let jsId = this.queryForm.condition.competitionId
      comRegistration.getSubCompetitions(jsId).then(res => {
        this.options.subName = res.data
      })
    },
    // 字典获取
    getOptions() {
      // 筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_PYCC", 'X_PYLB', 'X_XWLX', 'X_XXXS', 'X_YX', 'JSGL_JSJB', 'X_XQ']
      };
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            trainingCategory: "X_PYLB",
            degreeType: "JSGL_JSJB",
            formLearning: "X_XXXS",
            faculty: "X_YX",
            TrainingLevel: "X_PYCC",
            campus: "X_XQ"
          },
          res.data,
          this.options
        );
      });
    },
    // 模糊查询竞赛名称
    remoteMethodName(val) {
      if (val !== '') {
        this.options.competitionNames = []
        this.queryForm.condition.competitionId = val
        this.getCompetitionNames()
      } else {
        this.options.competitionNames = []
      }
    },
    // 工号改变获取数据
    remoteMethodOne(query) {
        if (!!query) {
            setTimeout(() => {
            findTeacherInfoList({
                condition: query,
                pageSize_: 100,
                pageNum_: 0
            }).then(res => {
                if (res && res.code == 200) {
                    res.data.list.forEach(row => {
                      row.name += '(' + row.code + ')';
                    })
                    this.options.approver = res.data.list
                }
            })
            }, 200);
        } else {
            this.options.approver = []
        }
    },
    // 合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3) {
            const _row = this.spanArr[rowIndex]
            const _col = _row > 0 ? 1 : 0
            return {
                rowspan: _row,
                colspan: _col
            };
        } else if (columnIndex === 13 || columnIndex === 14 || columnIndex === 15) {
            const _row = this.contentSpanArr[rowIndex]
            const _col = _row > 0 ? 1 : 0
            return {
                rowspan: _row,
                colspan: _col
            };
        }
    },
    postProjectInform(data) {
      this.options.profession = []
      competitionRegistrationApi.getSignList(data).then(res => {
        this.dataList = res.data.list
        this.queryForm.total_ = res.data.total_
        // 设定一个数组spanArr/contentSpanArr来存放要合并的格数，同时还要设定一个变量pos/position来记录
        this.spanArr = []
        this.contentSpanArr = []
        for (var i = 0; i < this.dataList.length; i++) {
            if (i === 0) {
                this.spanArr.push(1)
                this.pos = 0
                this.contentSpanArr.push(1)
                this.position = 0
            } else {
                // 判断当前元素与上一个元素是否相同(第1和第2列)
                if (this.dataList[i].signRecordId === this.dataList[i - 1].signRecordId) {
                    this.spanArr[this.pos] += 1
                    this.spanArr.push(0)
                } else {
                    this.spanArr.push(1)
                    this.pos = i
                }
                // 判断当前元素与上一个元素是否相同(第3列)
                if (this.dataList[i].signRecordId === this.dataList[i - 1].signRecordId) {
                    this.contentSpanArr[this.position] += 1
                    this.contentSpanArr.push(0)
                } else {
                    this.contentSpanArr.push(1)
                    this.position = i
                }
            }
        }
      })
    },
    // 根据年度获取竞赛名称
    changeYear(val) {
      this.getCompetitionNames()
    },
    getCompetitionNames() {
      let param = {
          "pageNum_": 1,
          "pageSize_": 10,
          "condition":{
              "projectName": this.queryForm.condition.competitionId,
              "year": this.queryForm.condition.year,
              "form": 1
          }
      }
      this.options.competitionNames = []
      competitionRegistrationApi.getCompetitionNames(param).then(res => {
          if (res.data.list) {
              res.data.list.forEach(el => {
                  this.options.competitionNames.push({
                      label: el.projectName,
                      value: el.id
                  })
              })
          }
      })
    },
    // 选拔不通过
    noSelection() {
        let params = {
            'ids': this.noPassList
        }
        competitionRegistrationApi.selectionFail(params).then(res => {
            if( res.code === 200) {
                this.$message.success(this.$t('internship.successfully'))
                this.postProjectInform(this.queryForm)
            }
        })
    },
    // 选拔完成
    selectionCompleted() {
        let params = {
            'competitionId': this.queryForm.condition.competitionId,
            'year': this.queryForm.condition.year
        }
        competitionRegistrationApi.selectComplete(params).then(res => {
            if( res.code === 200) {
                this.$message.success(this.$t('internship.successfully'))
                this.postProjectInform(this.queryForm)
            }
        })
    },
    // 筛选
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.postProjectInform(this.queryForm)
    },
    // 重置
    reset() {
      for (let key in this.queryForm.condition) {
        if (key === 'form' || key === 'year') {
            continue;
        }
        this.queryForm.condition[key] = '';
      }
      this.queryForm.condition.year = new Date().getFullYear()+''
      this.options.approver = []
      this.queryForm.pageNum_ = 1
      this.postProjectInform(this.queryForm)
    },
    // 轮询直到获取key值的接口返回
    cycleToGetKey() {
      setTimeout(() => {
        competiManagementApi.projectInformaExport({
          "year": this.queryForm.condition.year,
          "college": this.queryForm.condition.faculty,
          "name": this.queryForm.condition.name,
          "comLevel": this.queryForm.condition.comLevel,
          "comManager": this.queryForm.condition.comManager
        }).then(res => {
          if (res.success) {
            this.$refs.downloadRef.close();
            this.exportButton = false;
            this.normalDelayRequest(res.key, res.msg);
          } else {
            this.cycleToGetKey();
          }
        });
      }, 3000);
    },
    // 导出异步
    delayRequest(key, name) {
      setTimeout(() => {
        competiManagementApi.downloadGetKey(key, name).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path = '/api/competitionservice/competitionExport/file?path=' + res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // Normal导出异步
    normalDelayRequest(key, name) {
      setTimeout(() => {
        competiManagementApi.downloadGetKey(key).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =  '/api/competitionservice/competitionExport/file?path=' + res.data.path + '&name=' + name;
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    //  导出
    exportFile() {
      // 1、第一步：调该接口，获取key值以及msg中的文件名
      // 2、第二步：将key值放入接口传参
      // 3、第三步：传入path值以及name(msg中的文件名)值，下载文件
      // this.exportResult = null;
      // this.$refs.downloadRef.open();
      // this.exportButton = true;
      // this.cycleToGetKey();
      let params = {
          "form": 1,
          "faculty": this.queryForm.condition.faculty,
          "status": this.queryForm.condition.status,
          "year": this.queryForm.condition.year,
          "studentId":  this.queryForm.condition.studentId,
          "studentName": this.queryForm.condition.studentName,
          "competitionId": this.queryForm.condition.competitionId,
          "ids": this.noPassList
      }
      competitionRegistrationApi.exportGroupList(params)
    },
    handleSelectionChange(val) {
        this.noPassList = []
        val.forEach(item => {
            this.noPassList.push(item.signRecordId)
        })
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.queryForm.pageNum_ = 1
      this.postProjectInform(this.queryForm)
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.postProjectInform(this.queryForm)
    },
    // 人员变更
    publish(val) {
        this.compile = 'team'
        this.dataInfo = val
        this.indexKey = 2
    },
    // 返回列表主页
    changeExamTeam() {
        this.indexKey = 1
        this.queryForm.pageNum_ = 1
        this.postProjectInform(this.queryForm)
        // this.postCompetitionInform(this.queryForm)
    },
  }
}
</script>
<style scoped>

</style>